<?php
namespace app\finance\model;
use think\Db;
use app\common\model\Common;
class Finance extends Common
{
	/**
	* 收入估算
	*/
	public function income($where)
	{
		$income['order_money'] = $this->orderCount($where);
		$income['order_wait_money'] = $this->orderWaitMoney($where);
		$income['repair_money'] = $this->repairCount($where);
		$income['repair_wait_money'] = $this->repairWaitMoney($where);
		$income['order_repair'] = $this->doubleSum($income['order_money'], $income['repair_money']);
		return $income;
	}
	/**
	* 支出估算
	*/
	public function pay($where)
	{
		$sql = $this->expendLog($where);
		return Db::name('expendCate')->alias('ec')
		->join($sql,'ec.expend_cate_id = el.expend_cate_id','LEFT')
		->field('ec.expend_cate_id,ec.cat_name,ifnull(sum(el.money),0) as money')
		->where('ec.ty','in','0,2')
		->group('ec.expend_cate_id')->select();
	}
	/**
	* 销售总收入
	*/
	public function orderCount($where)
	{
		$orderMoney = $this->orderMoney($where);
		$orderId = $this->orderId($where);
		$orderGoodsMoney = $this->orderGoodsMoney($orderId);
		return $this->doubleReduce($orderMoney, $orderGoodsMoney);
	}
	/**
	* 销售待支付金额
	*/
	public function orderWaitMoney($where)
	{
		return Db::name('order')->where($where)->sum('stay_money');
	}
	/**
	* 维修总收入
	*/
	public function repairCount($where)
	{
		return Db::name('repair')->where($where)->where('state','in','3,4,5,6,8')->sum('repair_money-parts_money');
	}
	/**
	* 维修待支付金额
	*/
	public function repairWaitMoney($where)
	{
		return Db::name('repair')->where($where)->where('state','in','3,4,5,6,8')->sum('stay_money');
	}

	/********************************************************/
	/************************** 私有 ************************/
	/*******************************************************/
	
	/**
	* 支出统计
	*/
	private function expendLog($where)
	{
		if(isset($where['addtime']) && $where['addtime'] != ''){
			$data['addtime'] = $where['addtime'];
		}
		$sql = Db::name('expendLog')->field('expend_cate_id,money')->where($data)->select(false);
		return "($sql) as el";
	}
	/**
	* 满足条件的售货单id集合
	*/
	private function orderId($where)
	{
		return Db::name('order')->where($where)->column('order_id');
	}
	/**
	* 售货单总金额
	*/
	private function orderMoney($where)
	{
		return Db::name('order')->where($where)->sum('order_money');
	}
	/**
	* 售货单商品成本
	*/
	private function orderGoodsMoney($orderId)
	{
		return Db::name('orderGoods')->where('order_id','in',$orderId)->sum('buying_price*number');
	}
}